//    Copyright (C) 2013  <lugocreation@gmail.com>
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>
package org.jpgolay.wi.group;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PrinterJob;
import java.beans.PropertyVetoException;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.*;
import org.jpgolay.gui.iconBar.*;
import org.jpgolay.gui.progressBar.ProgressBar;
import org.jpgolay.gui.progressBar.SwingWorker;
import org.jpgolay.wi.user.User;
import org.jpgolay.wi.util.BrowserControl;
import org.jpgolay.wi.util.WIDate;

// Referenced classes of package org.jpgolay.wi.group:
//            GroupCRUD, GroupGUI, Group
public class GroupController {

    public GroupController() {
        id = "";
        action = 0;
        initComponent();
        date = new WIDate();
        actionOpen();
    }

    private boolean initComponent() {
        if (crud == null) {
            crud = new GroupCRUD();
        }
        if (gGui == null || gGui.isClosed()) {
            gGui = new GroupGUI();
            gGui.setIconifiable(true);
            gGui.setResizable(false);
            gGui.setMaximizable(false);
            gGui.setClosable(true);
            gGui.setVisible(true);
            gGui.toFront();
            gGui.getSaveMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent actionevent) {
                }
            });
            gGui.getNewMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionCreate();
                }
            });
            gGui.getOpenMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionOpen();
                }
            });
            gGui.getModifyMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionModify();
                }
            });
            gGui.getSaveMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionSave();
                }
            });
            gGui.getRemoveMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionRemove();
                }
            });
            gGui.getHelpMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionHelp();
                }
            });
            gGui.getPrintMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    PrinterJob pj = PrinterJob.getPrinterJob();
                    if (pj.printDialog()) {
                        actionPrint();
                    }
                }
            });
            gGui.getIconBar1().addAnswerListener(new AnswerListener() {
                public void create(AnswerEvent e) {
                    actionCreate();
                }

                public void open(AnswerEvent e) {
                    actionOpen();
                }

                public void modify(AnswerEvent e) {
                    actionModify();
                }

                public void save(AnswerEvent e) {
                    actionSave();
                }

                public void remove(AnswerEvent e) {
                    actionRemove();
                }

                public void print(AnswerEvent e) {
                    actionPrint();
                }

                public void help(AnswerEvent e) {
                    actionHelp();
                }
            });
            return true;
        }
        if (gGui.isIcon()) {
            try {
                gGui.setIcon(false);
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            }
        }
        gGui.toFront();
        return false;
    }

    private void actionCreate() {
        if (action != 2) {
            action = 1;
            gGui.initFields();
            gGui.setCellEditable(true);
        } else {
            JOptionPane.showMessageDialog(gGui, "Enregistrer les modifications !");
        }
    }

    private void actionOpen() {
        gGui.setCellEditable(false);
        action = 0;
        getGroups();
    }

    private void actionModify() {
        if (action == 1) {
            JOptionPane.showMessageDialog(gGui, "Cr\351ation en cours !");
        } else {
            action = 2;
            gGui.setCellEditable(true);
        }
    }

    private void actionSave() {
        if (action == 2 || action == 1) {
            setGroup();
        } else {
            JOptionPane.showMessageDialog(gGui, "Aucunes donn\351es \340 sauvegarder !");
        }
    }

    private void actionRemove() {
        if (action == 2) {
            remove();
        } else {
            JOptionPane.showMessageDialog(gGui, "Aucunes donn\351es \340 supprimer !");
        }
    }

    private void actionPrint() {
    }

    private void actionHelp() {
        BrowserControl.displayURL("www.ifacile.com");
    }

    private void getGroups() {
        String ID = id;
        SwingWorker worker = new SwingWorker() {
            public Object construct() {
                startProgressBar();
                groupList = new ArrayList(crud.findAll());
                if (groupList != null && groupList.size() > 0) {
                    Iterator it = groupList.iterator();
                    data = new Object[groupList.size()][4];
                    for (int line = 0; it.hasNext(); line++) {
                        group = (Group) it.next();
                        data[line][0] = group.getId().toString();
                        data[line][1] = group.getName();
                        data[line][2] = group.getRole();
                        data[line][3] = group.getNote();
                    }

                    gGui.setData(data);
                } else {
                    JOptionPane.showMessageDialog(gGui, "Aucunes donn\351es enregistr\351es !");
                }
                stopProgressBar();
                return null;
            }
        };
        worker.start();
    }

    private void setGroup() {
        SwingWorker worker = new SwingWorker() {
            public Object construct() {
                startProgressBar();
                data = gGui.getData();
                for (int i = 0; i < data.length; i++) {
                    if (data[i][0].equals(new String("")) && !data[i][1].equals(new String(""))) {
                        crud.create();
                        group = crud.getData();
                        group.setName((String) data[i][1]);
                        group.setRole((String) data[i][2]);
                        group.setNote((String) data[i][3]);
                        group.setLastUser(user.getId().toString());
                        crud.setData(group);
                        crud.modify();
                    } else if (!data[i][0].equals(new String("")) && crud.find((String) data[i][0])) {
                        group = crud.getData();
                        group.setName((String) data[i][1]);
                        group.setRole((String) data[i][2]);
                        group.setNote((String) data[i][3]);
                        group.setLastUser(user.getId().toString());
                        crud.setData(group);
                        crud.modify();
                    }
                }

                stopProgressBar();
                return null;
            }
        };
        worker.start();
    }

    private void remove() {
        if (gGui.getGroup().getValueAt(gGui.getGroup().getSelectedRow(), 0) != null) {
            int reponse = JOptionPane.showConfirmDialog(gGui, "Voulez-vous vraiment supprimer le groupe s\351l\351ctionn\351 ?\nATTENTION toutes les agences ainsi que leurs biens associ\351s et tous\nles utilisateurs seront d\351finitivement perdus !", "Confirmation", 1, 2, null);
            switch (reponse) {
                case 0: // '\0'
                    String id = (String) gGui.getGroup().getValueAt(gGui.getGroup().getSelectedRow(), 0);
                    if (crud.find(id)) {
                        group = crud.getData();
                        if (crud.remove()) {
                            getGroups();
                        } else {
                            JOptionPane.showMessageDialog(gGui, "Impossible de supprimer le groupe s\351l\351ctionn\351 (" + id + ") !" + "\nUn autre utilisateur l'a peut-\352tre modifi\351 entre temps.");
                        }
                    } else {
                        JOptionPane.showMessageDialog(gGui, "Impossible de trouver le groupe s\351l\351ctionn\351 (" + id + ") !" + "\nUn autre utilisateur l'a peut-\352tre supprimer entre temps.");
                    }
                    break;
            }
        } else {
            JOptionPane.showMessageDialog(gGui, "Aucun groupe n'est s\351l\351ctionn\351  !");
        }
    }

    public boolean init() {
        if (gGui == null || gGui.isClosed()) {
            boolean result = initComponent();
            if (result) {
                setLaw();
            }
            return result;
        }
        if (gGui.isIcon()) {
            try {
                gGui.setIcon(false);
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            }
        }
        gGui.toFront();
        return false;
    }

    public void iconified() {
        if (gGui != null) {
            gGui.setVisible(false);
        }
    }

    public void unIconified() {
        if (gGui != null) {
            gGui.setVisible(true);
        }
    }

    public void maximizeFrame() {
        try {
            gGui.setSelected(true);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    }

    private void startProgressBar() {
        if (pb == null) {
            pb = new ProgressBar(null, false);
            pb.setLocationRelativeTo(gGui);
            gGui.setEnabled(false);
            pb.setVisible(true);
            pb.start();
        } else {
            gGui.setEnabled(false);
            pb.setVisible(true);
            pb.start();
        }
    }

    private void stopProgressBar() {
        if (!pb.isStop()) {
            pb.stop();
            pb.setVisible(false);
            gGui.setEnabled(true);
        }
    }

    private void setLaw() {
        String b = Long.toBinaryString(user.getAccess().intValue());
        int position = b.length();
        if ((position -= 10) >= 0 && b.charAt(position) == '1') {
            gGui.getNewMI().setEnabled(true);
            gGui.getModifyMI().setEnabled(true);
            gGui.getRemoveMI().setEnabled(true);
            gGui.getSaveMI().setEnabled(true);
            gGui.getIconBar1().setEnabledCreate(true);
            gGui.getIconBar1().setEnabledModify(true);
            gGui.getIconBar1().setEnabledRemove(true);
            gGui.getIconBar1().setEnabledSave(true);
        }
    }

    public void setUser(User user) {
        this.user = user;
        setLaw();
    }

    public GroupGUI getGUI() {
        return gGui;
    }

    public void setDefaultMainFrame(JFrame desktop) {
        this.desktop = desktop;
    }
    private GroupGUI gGui;
    private GroupCRUD crud;
    private Group group;
    private User user;
    private Dimension screen;
    private WIDate date;
    private ProgressBar pb;
    private String id;
    private int action;
    private final int CREATE = 1;
    private final int MODIFY = 2;
    private ArrayList groupList;
    private Object data[][];
    private JFrame desktop;
}
